<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { postAdd } from '@/apis/apis.js'
import { getFormattedDate } from '@/utils/utils.js'

const form = ref({
  name: '',
  password: '',
  email: '',
  remark: '',
  gender: -1
})
const formRef = ref(null)
const rules = ref({
  name: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入用户名'
    },
    {
      min: 2,
      max: 10,
      trigger: 'blur',
      message: '请输入用户名（长度为2-10个字符）'
    }
  ],
  password: [
    {
      required: true,
      trigger: 'blur',
      message: '请输入密码'
    }
  ]
})

const handleAdd = () => {
  formRef.value.validate(async (isValid) => {
    if (isValid) {
      try {
        const res = await postAdd({
          ...form.value,
          create_time: getFormattedDate()
        })
        console.log(res)
        if (!res.status) {
          ElMessage({ type: 'info', message: res.msg })
        }
        else {
          ElMessage({ type: 'success', message: res.msg })
          handleReset()
        }
      }
      catch (err) {
        ElMessage({ type: 'info', message: '网络异常' })
      }
      
    }
  })
}
const handleReset = () => {
  form.value = {
    name: '',
    password: '',
    email: '',
    remark: '',
    gender: -1
  }
}
</script>

<template>
  <el-form :model="form" :rules="rules" ref="formRef" label-width="50" hide-required-asterisk>
    <el-form-item prop="name" label="名称">
      <el-input v-model.trim="form.name" placeholder="请填写名称" />
    </el-form-item>
    <el-form-item prop="password" label="密码">
      <el-input type="password" show-password placeholder="请填写密码" v-model.trim="form.password" />
    </el-form-item>
    <el-form-item prop="email" label="邮箱">
      <el-input v-model.trim="form.email" />
    </el-form-item>
    <el-form-item prop="remark" label="备注">
      <el-input type="textarea" v-model.trim="form.remark" />
    </el-form-item>
    <el-form-item prop="gender" label="性别">
      <el-radio-group v-model="form.gender">
        <el-radio :value="-1">未知</el-radio>
        <el-radio :value="0">男</el-radio>
        <el-radio :value="1">女</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleAdd">添加</el-button>
      <el-button @click="handleReset">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped></style>
